package com.lc.projects.sample.plan;

import java.util.HashMap;
import java.util.Map;

public class TestClone {
	public static void main(String[] args) {

		System.out.println("----------map------------");
		Map<String, Object> m1 = new HashMap<>();
		m1.put("a", 1);
		Map<String, Object> m2 = new HashMap<>();
		m2.putAll(m1);
		m2.put("b", 2);

		System.out.println(m1);
		System.out.println(m2);

		System.out.println("----------person------------");

		Test t = new Test("testa");
		Person p1 = new Person("a", 1);
		p1.setTest(t);
		System.out.println(p1);
		System.out.println("------after----");
		Person p2 = (Person) p1.clone();
		p2.setAge(3);
		p2.getTest().changeName();
		System.out.println(p1);
		System.out.println(p2);

	}
}

// clone后类变量指向的是同一个地址，如果要不影响 需要深度clone
class Person implements Cloneable {
	private String name;
	private int age;
	private Test test;

	public Test getTest() {
		return test;
	}

	public void setTest(Test test) {
		this.test = test;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public Person() {
		super();
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", test=" + test + "]";
	}

	@Override
	protected Object clone() {
		Person p = null;
		try {
			p = (Person) super.clone();
			p.setTest((Test) test.clone());
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return p;
	}
}

class Test implements Cloneable {
	private String name;

	public void changeName() {
		this.name = name + " change";
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Test(String name) {
		super();
		this.name = name;
	}

	@Override
	public String toString() {
		return "Test [name=" + name + "]";
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}

}